package com.microservice.auth.controller;

import com.microservice.auth.form.UserLoginDTO;
import com.microservice.auth.service.ILoginService;
import com.microservice.core.domain.AjaxResult;

import com.microservice.core.utils.StringUtils;
import com.microservice.model.system.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户登录接口
 */
@RestController
@RequestMapping("/user")
public class LoginController {

    @Resource
    private ILoginService loginService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, HttpServletResponse response) {
       User user = loginService.getUserInfo(userLoginDTO.getUsername(), userLoginDTO.getPassword());
       return AjaxResult.success(loginService.createToken(user, response));
    }

    /**
     * PreAuthorize配合@EnableMethodSecurity(prePostEnabled = true)使用
     * EnableMethodSecurity注解位于SecurityConfig类中
     * PreAuthorize("hasAuthority('/user/logout')")要求用户有退出登录的权限,这个权限在哪里添加的呢？看下面
     * @see com.microservice.auth.jwt.userDetails.AccountUserDetailsService#loadUserByUsername(String)
     */
    @PreAuthorize("hasAuthority('/user/logout')")
    @GetMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        String accessToken = loginService.getAccessToken(request);
        if(StringUtils.isNotEmpty(accessToken)){
             loginService.logout(accessToken);
        }
        return AjaxResult.success();
    }
}
